package com.example.demo.service;

import com.example.demo.entity.*;
import com.example.demo.mapper.CustomerMapper;
import com.example.demo.mapper.LogsMapper;
import com.example.demo.mapper.RunTableMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service
public class RunTableServiceImpl implements RunTableService{


    @Autowired
    RunTableMapper runTableMapper;
    @Autowired
    CustomerMapper customerMapper;

    @Override
    @Transactional
    public JsonResult startRunTable(WorkTable workTable) {
        JsonResult json = new JsonResult();
//        Date endtime = runTableMapper.getEndDate(workTable.getPhone());
//        Date nowDate = new Date();
//        long end = endtime.getTime();
//        long now = nowDate.getTime();
//        long time = (now-end)/1000;
//        if(time>10*3600){
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        workTable.setStartTime(date);
        workTable.setUpdateTime(date);
        runTableMapper.startRunTable(workTable);
        customerMapper.endAllLogsWork(workTable.getPhone());
        customerMapper.saveWorkLogs(workTable);
//        }else {
//            json.setMessage("距上次结束时间不足10小时");
//        }
        json.setMessage("开始成功");
        json.setSuccess(true);
        return json;
    }

    @Autowired
    LogsMapper logsMapper;

    @Override
    @Transactional
    public JsonResult updateMemberWork(WorkLogs workLogs) {
        JsonResult json = new JsonResult();
//        WorkLogs workLogs = new WorkLogs();
//        workTable.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        runTableMapper.updateMemberWorkLog(workLogs);
        //更新钱包
        customerMapper.updateAWalletlogs(workLogs);
        //更新工作记录
        customerMapper.updateWorkNoLogsAgain(workLogs);
        logsMapper.insertWorkLogs(workLogs);
        json.setData(workLogs.getActualAmount());
        json.setSuccess(true);
        return json;
    }

    @Override
    @Transactional
    public JsonResult endMemberWork(WorkTable workTable) {
        JsonResult json = new JsonResult();
        //当前时间
        Date nowDate = new Date();
        //更新时间
        Date date = runTableMapper.getStartTime(workTable.getPhone());
        //已进行的时间
        Integer useDate = runTableMapper.getUseDate(workTable.getPhone());
        //已挣得的钱
        Integer money = runTableMapper.getUseMoney(workTable.getPhone());
        Long a = (nowDate.getTime()-date.getTime())/1000;
        BaseInfo baseInfo = customerMapper.getBaseInfo();
        Integer result = 0;
        if(a+useDate>12*3600){
            double max = (12*3600-workTable.getAllTime()) *baseInfo.getEarnPerSecondMaxMember();
            double min = (12*3600-workTable.getAllTime()) *baseInfo.getEarnPerSecondMinMember();
            result = (int)(min + (int)(Math.random() * ((max - min) + 1)));
            Integer earnMoney = result+ money;
            workTable.setEarnMoney(earnMoney);
            workTable.setTime(Long.valueOf(12*3600));
            long updatek = date.getTime()+(12*3600-useDate)*1000;
            String k = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(updatek));//更新结束时间
            workTable.setUpdateTime(k);
            workTable.setEndTime(k);
        }else {
            double max = a *baseInfo.getEarnPerSecondMaxMember();
            double min = a *baseInfo.getEarnPerSecondMinMember();
            result = (int)(min + (int)(Math.random() * ((max - min) + 1)));
            Integer earnMoney = result+ money;
            workTable.setEarnMoney(earnMoney);
            workTable.setTime(a+useDate);
            String updateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            workTable.setUpdateTime(updateTime);
            workTable.setEndTime(updateTime);
        }
        runTableMapper.endMemberWork(workTable);
        //更新钱包
        customerMapper.updateAWallet(workTable.getPhone(),result);
        workTable.setEarnMoney(result);
        customerMapper.updateWorkLogs2l(workTable);
        json.setData(workTable.getEarnMoney());
        json.setSuccess(true);
        return json;
    }

    @Override
    @Transactional
    public void startRunTableAgain(Integer id) {
        WorkTable workTable = new WorkTable();
        workTable.setId(String.valueOf(id));
        workTable.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        workTable.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        runTableMapper.startRunTableAgain(workTable);
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        workTable.setStartTime(date);
        //通过id获取手机号码
        String phone = runTableMapper.getPhone(id);
        workTable.setPhone(phone);
        //结束记录
        customerMapper.endAllLogsWork(workTable.getPhone());
        //重新开始
        customerMapper.saveWorkLogs(workTable);
    }

    @Override
    @Transactional
    public JsonResult loginMemberJudge(String phone) {
        JsonResult json = new JsonResult();
        Map<String,Object> map = new HashMap<>();
        //获取最后一条数据的全部信息
        WorkTable workTable = runTableMapper.getWorkTableAll(phone);
        if (workTable!=null&&workTable.getState()==0){
            map.put("is_have",4);
            map.put("allowTime", 12*3600-workTable.getAllTime());
            map.put("WorkTable",workTable);
            map.put("workedMoney",workTable.getEarnMoney());
            map.put("msg","订单正在进行");
        }else{
            //判断时间是否足够12小时
            if(workTable!=null&&workTable.getAllTime()<12*3600){
                map.put("is_have",3);
                map.put("allowTime", 12*3600-workTable.getAllTime());
                map.put("workedMoney",workTable.getEarnMoney());
                map.put("msg","已开始开始工作！！还剩余"+(12*3600-workTable.getAllTime())+"秒试运行时间");
            }else{
                //查询当前时间
                long now = (new Date()).getTime();
                //查询结束时间
                Date l = runTableMapper.getEndDate(phone);
                if(l==null){
                    map.put("is_have",2);
                    map.put("allowTime", 12*3600);
                    map.put("msg","还没有开始工作！！");
                }else {
                    long end = (l).getTime();
                    // 判断结束时间是否超过10小时
                    long time = (now-end)/1000;
                    if(time>10*3600){
                        map.put("is_have",2);
                        map.put("allowTime", 12*3600);
                        map.put("msg","还没有开始工作！！");
                    }else {
                        map.put("is_have",1);
                        map.put("allowTime",10*60*60-time);
                        map.put("msg","结束没有超过10小时，请10小时后再工作，还剩"+(10*60*60-time));
                    }
                }
            }
        }
        json.setSuccess(true);
        json.setData(map);
        return json;
    }

    @Override
    @Transactional
    public  JsonResult getError(Integer error,String phone) {
        JsonResult json = new JsonResult();
        WorkLogs workLogs = new WorkLogs();
        // todo 调用接口
        workLogs.setPhone(phone);
        workLogs.setCallMethod("customer/getError");
        workLogs.setCallName("会员再次登录获取");
        BaseInfo baseInfo = customerMapper.getBaseInfo();
        if(error==0){//断网
            String id = runTableMapper.getRuningTable(phone);
            if(id!=null){
                runTableMapper.endRuningTable(id);
            }
        }else if(error==1){//正常
            //查询出上一次更新的时间
            WorkTable workTable = runTableMapper.getWorkTableAll(phone);
            workLogs.setStartDate(workTable.getUpdateTime());
            workLogs.setUpdateBeforeDate(workTable.getAllTime());
            workLogs.setBeforeUpAmount(workTable.getEarnMoney());
            if(workTable!=null){
                //计算时间长度
                long now = (new Date()).getTime();
                workLogs.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//                long update = runTableMapper.getStartTime2(workTable.getId()).getTime();
                long update = workTable.getUpdateTime2().getTime();
                //未连接的访问时间
                long time = (now-update)/1000;

                //总共执行时间
                Integer eleTime = workTable.getAllTime()+Integer.valueOf(String.valueOf(time));
//                //判断是否超出12小时
                if(eleTime > 12*3600){
                    //按照12小时计算
                    double max = (12*3600-workTable.getAllTime()) *baseInfo.getEarnPerSecondMaxMember();
                    double min = (12*3600-workTable.getAllTime()) *baseInfo.getEarnPerSecondMinMember();
                    Integer result = (int)(min + (int)(Math.random() * ((max - min) + 1)));
                    Integer earnMoney = result+workTable.getEarnMoney();
                    workLogs.setWorkDate(12*3600-workTable.getAllTime());
                    // todo
                    workLogs.setActualAmount(result);
                    workLogs.setAfterUpAmount(earnMoney);
                    long updatek = update+(12*3600-workTable.getAllTime())*1000;
                    // todo
                    workLogs.setUpdateAfterDate(workTable.getAllTime()+workLogs.getWorkDate());
                    String k = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(updatek));//更新结束时间
                    workLogs.setEndDate(k);
                    WorkTable w = new WorkTable();
                    w.setAllTime(12*3600);
                    w.setPhone(phone);
                    w.setEndTime(k);
                    w.setUpdateTime(k);
                    w.setEarnMoney(earnMoney);
                    runTableMapper.endMemberWorkLog(workLogs);
                    //更新钱包
                    customerMapper.updateAWallet(phone,result);
                    w.setEarnMoney(result);
                    customerMapper.updateWorkLogsAgain(w);
//                    //结束记录
                    customerMapper.endStatic(phone,time);
                    logsMapper.insertWorkLogs(workLogs);
                }else {
                    //价格区间
                    double max = time*baseInfo.getEarnPerSecondMaxMember();
                    double min = time*baseInfo.getEarnPerSecondMinMember();
                    Integer result = (int)(min + (int)(Math.random() * ((max - min) + 1)));
                    // todo
                    workLogs.setWorkDate(time);
                    workLogs.setActualAmount(result);
                    workLogs.setAfterUpAmount(result+workLogs.getBeforeUpAmount());
                    workLogs.setUpdateAfterDate(time+workLogs.getUpdateBeforeDate());
                    WorkTable w = new WorkTable();
                    w.setPhone(workLogs.getPhone());
                    w.setAllTime(Integer.valueOf(String.valueOf(workLogs.getUpdateAfterDate())));
                    w.setEarnMoney(workLogs.getActualAmount());
                    w.setTime(workLogs.getWorkDate());
                    w.setUpdateTime(workLogs.getEndDate());
                    runTableMapper.updateMemberWorkLog(workLogs);
//                    //更新钱包
                    customerMapper.updateAWallet(phone,result);
//                    //更新工作记录
                    customerMapper.updateWorkLogsAgain(w);
                    logsMapper.insertWorkLogs(workLogs);
                }

            }
        }
        json.setSuccess(true);
        return json;
    }

    //*********************************************************************************************************************
    @Override
    public WorkTable getWorkTable(String phone) {
        return runTableMapper.getWorkTable(phone);
    }

    @Override
    public Date getStartTime(String phone) {
        return runTableMapper.getStartTime(phone);
    }


    //    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

}
